package com.gwtgeo.ui.client.mvp.searchform;

import java.util.Map;

import net.customware.gwt.dispatch.client.DispatchAsync;
import net.customware.gwt.presenter.client.EventBus;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasText;
import com.google.inject.Inject;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowTypeEnum;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowedDisplay;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowedPresenter;
import com.gwtgeo.ui.shared.event.SearchFinishedEvent;
import com.gwtgeo.ui.shared.rpc.Search;
import com.gwtgeo.ui.shared.rpc.SearchResult;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.HasClickHandlers;

public class SearchFormPresenter extends
		WindowedPresenter<SearchFormPresenter.Display> {

	private final DispatchAsync dispatcher;

	public interface Display extends WindowedDisplay {

		HasText getSearchString();

		void clear();

		HasClickHandlers getSearchButtonClick();

		boolean validate();
	}

	@Inject
	public SearchFormPresenter(Display display, EventBus eventBus,
			final DispatchAsync dispatcher) {
		super(display, eventBus);
		this.dispatcher = dispatcher;
		this.init(null);
	}

	@Override
	public void init(Map<String, Object> params) {
	}
	
	@Override
	public WindowTypeEnum getType() {
		return WindowTypeEnum.SEARCH_FORM;
	}

	@Override
	protected void onBind() {
		super.onBind();
		this.registerHandler(this.display.getSearchButtonClick()
				.addClickHandler(new ClickHandler() {

					@Override
					public void onClick(ClickEvent event) {

						if (display.validate()) {

							dispatcher.execute(new Search(display
									.getSearchString().getText()),
									new AsyncCallback<SearchResult>() {

										@Override
										public void onFailure(Throwable caught) {
											Log
													.error("Handle Failure:",
															caught);
										}

										@Override
										public void onSuccess(
												SearchResult result) {
											eventBus
													.fireEvent(new SearchFinishedEvent(
															result
																	.getLocations()));
											display.clear();
										}

									});
						}
					}
				}));

	}

	@Override
	protected void onRevealDisplay() {

	}

	@Override
	protected void onUnbind() {

	}

}
